package com.ddyx.service.impl.user;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jms.Destination;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ddyx.entity.Customer;
import com.ddyx.entity.user.UEmploye;
import com.ddyx.entity.user.UStore;
import com.ddyx.mapper.CustomerContactMapper;
import com.ddyx.mapper.CustomerMapper;
import com.ddyx.mapper.WxUserMapper;
import com.ddyx.mapper.user.UEmployeMapper;
import com.ddyx.mapper.user.UStoreMapper;
import com.ddyx.service.user.UEmployeService;
import com.ddyx.util.EventTag;
import com.ddyx.util.MQUtil;
import com.ddyx.util.MyBeanUtils;
import com.ddyx.util.RequestForm;
import com.ddyx.util.ResponseForm;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
@Slf4j
public class UEmployeServiceImpl implements UEmployeService {
	
	private static ObjectMapper jsonMapper = new ObjectMapper();

	@Resource
	UEmployeMapper uEmployeMapper;
	@Resource
	UStoreMapper uStoreMapper;
	@Resource
	WxUserMapper wxUserMapper;
	@Resource
	JmsTemplate jmsTemplate;
	@Resource
	Destination tmpMsgDestination;
	@Resource
	Destination topicDestination;
	@Resource
	CustomerMapper customerMapper;
	@Resource
	CustomerContactMapper ccMapper;
	
	@Transactional
	@Override
	public ResponseForm addEmploye(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if(param.getData()!=null) {
			Map paramMap = (Map) param.getData();
			UEmploye bean = new UEmploye();
			MyBeanUtils.populate(bean, paramMap);
			String storeNo= (String) paramMap.get("storeNo");
			try {
				
				if(!StringUtils.isNotBlank(storeNo)){
					result.setCode("1");
					result.setMessage("店铺不能为空");
					return result;
				}
				
				uEmployeMapper.insertSelective(bean);
				bean.setEmployeNo(String.valueOf(bean.getEmployeId()));
				uEmployeMapper.updateByPrimaryKeySelective(bean);
				
			} catch (Exception e) {
				e.printStackTrace();
				result.setStatus(false);
				result.setMessage("操作有误");
				log.error("操作有误");
			}
		}
		return result;
	}

	@Override
	public ResponseForm listEmploye(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if(param.getData()!=null) {
			Map paramMap = (Map) param.getData();
			try {
				
				paramMap = com.ddyx.util.Page.parsePage(paramMap);
				Example example = new Example(UEmploye.class);
				Criteria c = example.createCriteria();
				Criteria c1 = example.createCriteria();
				String searchName= (String) paramMap.get("searchName");
				
				String storeNo= (String) paramMap.get("storeNo");
				
				Object roleId= paramMap.get("roleId");
				
				if(StringUtils.isNotBlank(storeNo)){
					c.andEqualTo("storeNo", storeNo);
				}
				
				if(roleId!=null){
					c.andEqualTo("roleId", roleId);
				}
				example.and(c);
				if(StringUtils.isNotBlank(searchName)){
					c1.orLike("employeNo", "%"+ searchName +"%");
					c1.orLike("mobile", "%"+ searchName +"%");
					c1.orLike("employeName", "%"+ searchName +"%");
					example.and(c1);
				}
				
				com.ddyx.util.Page.parsePage(paramMap);
				Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
				List<UEmploye> list=uEmployeMapper.selectByExample(example);
				for (int i = 0; i < list.size(); i++) {
					UEmploye ue = list.get(i);
					UStore ustore = new UStore();
					ustore.setStoreNo(ue.getStoreNo());
					ustore=uStoreMapper.selectOne(ustore);
					if(ustore!=null){
						ue.setStoreName(ustore.getStoreName());
					}
				}
				
				result.setData(list);
				result.setTotal((int) pageHelper.getTotal());
				
			} catch (Exception e) {
				e.printStackTrace();
				result.setStatus(false);
				result.setMessage("操作有误");
				log.error("操作有误");
			}
		}
		return result;
	}

	@Transactional
	@Override
	public ResponseForm updateEmploye(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if(param.getData()!=null) {
			Map paramMap = (Map) param.getData();
			UEmploye bean = new UEmploye();
			MyBeanUtils.populate(bean, paramMap);
			try {
				uEmployeMapper.updateByPrimaryKeySelective(bean);
			} catch (Exception e) {
				e.printStackTrace();
				result.setStatus(false);
				result.setMessage("操作有误");
				log.error("操作有误");
			}
		}
		return result;
	}

	@Override
	public ResponseForm checkEmploye(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if(param.getData()!=null) {
			Map paramMap = (Map) param.getData();
			UEmploye bean = new UEmploye();
			MyBeanUtils.populate(bean, paramMap);
			try {
				UEmploye e = uEmployeMapper.selectOne(bean);
				if(e ==null){
					result.setCode("1");
					result.setMessage("用户不存在或密码错误");
					return result;
				}
				//获取用户对应的门店信息
				// 管理员没有门店
				if(e.getRoleId()!=3){
					UStore uStore = new UStore();
					uStore.setStoreNo(e.getStoreNo());
					UStore uBean  = uStoreMapper.selectOne(uStore);
					if(uBean==null){
						result.setCode("1");
						result.setMessage("门店有误");
						return result;
					}
					e.setStoreName(uBean.getStoreName());
					e.setStoreId(uBean.getStoreId());
					e.setCompanyId(uBean.getCompanyId());
					e.setLineStatus(uBean.getLineStatus());
				}
				
				result.setData(e);
			} catch (Exception e) {
				e.printStackTrace();
				result.setStatus(false);
				result.setMessage("操作有误");
				log.error("操作有误");
			}
		}
		return result;
	}

	@Override
	public ResponseForm login(RequestForm param) {
		ResponseForm result = new ResponseForm();
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		try {
			UEmploye bean = new UEmploye();
			//MyBeanUtils.populate(user, paramMap);
			bean.setMobile(String.valueOf(paramMap.get("mobile")));
			bean.setStatus(0);
			bean = uEmployeMapper.selectOne(bean);
			if(bean==null){
				result.setStatus(false);
				result.setCode("1");
				result.setMessage("用户不存在");
				log.error("用户不存在");
				return result;
			}
			if(!bean.getPassword().endsWith(String.valueOf(paramMap.get("password")))){
				result.setStatus(false);
				result.setCode("1");
				result.setMessage("请检查密码");
				log.error("请检查密码");
				return result;
			}
			result.setData(bean);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage("操作错误");
			log.error("操作错误");
		}
		return result;
	}

	@Override
	public ResponseForm getEmployeById(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if(param.getData()!=null) {
			Map paramMap = (Map) param.getData();
			UEmploye bean = new UEmploye();
			MyBeanUtils.populate(bean, paramMap);
			try {
				bean=uEmployeMapper.selectByPrimaryKey(bean.getEmployeId());
				result.setData(bean);
			} catch (Exception e) {
				e.printStackTrace();
				result.setStatus(false);
				result.setMessage("操作有误");
				log.error("操作有误");
			}
		}
		return result;
	}
	
	

	
	@SuppressWarnings("unchecked")
	@Override
	public ResponseForm getGuide(RequestForm param) throws Exception {
		ResponseForm result = new ResponseForm();
		try {
			Date date = new Date();
			Map paramMap = (Map) param.getData();
			paramMap.put("createTime", date);
			String employeNo = (String) paramMap.get("employeNo");
			String storeNo = (String) paramMap.get("storeNo");
			String wxUid = (String) paramMap.get("wxUid");
			Map map = new HashMap<>();
			//如果employNo不为空,返回导购信息
			if(StringUtils.isNotBlank(employeNo)) {
				map = ccMapper.getGuideByStoreNo(paramMap);
				//如果拿到导购信息就返回
				if (map==null) {
					result.setCode(EventTag.NEWCUSTOMER);
					map = uEmployeMapper.getGuide(paramMap);
					if(map==null) {
						result.setMessage("the employe is not exist!");
						result.setStatus(false);
						return result;
					}
					// mq同步 客户导购关系
					paramMap.put("actionType", EventTag.CUSTCONTACT);
					MQUtil.sendObMsg(paramMap, jmsTemplate, topicDestination);
				}
				result.setData(map);
			}
			//添加新店员
			customerMapper.newCustomer(paramMap);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMessage("操作有误");
			log.error("操作有误");
		}
		return result;
	}
	// //发送 服务通知
	// //获取Store信息
	// List list = new ArrayList<>();
	// Map<String, Object> keyword = new HashMap<>();
	// TemplateMessageParam tmpMsgParam = new TemplateMessageParam();
	// Store store = new Store();
	// store.setStoreNo(storeNo);
	// store = storeMapper.selectOne(store);
	// WxUser wxUser = new WxUser();
	// wxUser.setWxUid(wxUid);
	// wxUser = wxUserMapper.selectOne(wxUser);
	// if(map!=null&&store!=null) {
	// list.add(new KeyWord((String) map.get("nickName"),EventTag.BLACK));//导购姓名
	// list.add(new KeyWord(store.getStoreName(), EventTag.BLACK));//门店名
	// list.add(new KeyWord(store.getLocation(), EventTag.BLACK)); //门店地址
	// list.add(new KeyWord(store.getPhoneNumber(), EventTag.BLACK));
	//
	// int i = 1;
	// for (Object o : list) {
	// keyword.put("keyword"+i, o);
	// i++;
	// }
	// //设置参数
	// tmpMsgParam.setTouser(wxUser.getOpenId());
	// tmpMsgParam.setForm_id((String) paramMap.get("formId"));
	// tmpMsgParam.setTemplate_id(PropertiesUtil.getProperty(EventTag.GUIDETEMP+"TMP_ID"));
	// tmpMsgParam.setData(keyword);
	// tmpMsgParam.setEmphasis_keyword("keyword2.DATA");
	// String json = jsonMapper.writeValueAsString(tmpMsgParam);
	// //MQ异步发送
	// MQUtil.sendJsonMsg(json, jmsTemplate, tmpMsgDestination);
	// }else {
	// result.setMessage("操作成功!由于参数错误,服务通知发送失败!!");
	// }
	
}
